<?php

/*
 * To change this template, choose Tools | Templates
 * 
 */
Yii::import('application.extensions.Apiv3._base.BaseApiFunctionality');

class authApiFunctionality extends BaseApiFunctionality {
    /* --------------- Start  GET Actions --------------------- */


    /* --------------- End GET Actions ------------------------ */


    /* --------------- Start POST Actions --------------------- */

    function login() {
        if ($this->validPostRequest()) {
            if (empty($_POST['user_name']) && empty($_POST['password'])) {
                $data = new AQResult(501, 'Please enter a username and password.');
                AQApiResponder::Respond($data, date('m-d-Y'));
            }

            if (empty($_POST['user_name'])) {
                $data = new AQResult(501, 'Please enter a username.');
                AQApiResponder::Respond($data, date('m-d-Y'));
            }

            if (empty($_POST['password'])) {
                $data = new AQResult(501, 'Please enter a password.');
                AQApiResponder::Respond($data, date('m-d-Y'));
            }


            $username = $_POST['user_name'];
            $password = $_POST['password'];

// Find the user
            // $user = Users::model()->find('LOWER(username)=?', array(strtolower($username)));
            $user = Users::model()->with(array(
                        'userHasRoles' => array(
                            // we don't want to select userhasroles field
                            'select' => false,
                            // but want to get only users with role id 2
                            'joinType' => 'INNER JOIN',
                            'condition' => 'userHasRoles.role_id=' . Roles::APPUSER,
                        ),
                    ))->find('LOWER(username)=?', array(strtolower($username)));

            if ($user === null) {
// Error: Unauthorized
                if (empty($data)) {
                    $data = new AQResult(501, 'User not found. Please check the username and try again.');
                }
                AQApiResponder::Respond($data, date('m-d-Y'));
            } else if (!$user->validatePassword($password)) {
// Error: Unauthorized
                $data = new AQResult(501, 'Incorrect Password. Please check the password you provided and try again.');
                AQApiResponder::Respond($data, date('m-d-Y'));
            }else{
              $user_id = $user->getAttribute('id');

            if ($user_id) {
                $data = self::getAuthKey($user_id);
            } else {
                $data = new AQResult(501, 'Unable to authenticate user. Please check the username and password and try again.');
            }  
            }

            

            AQApiResponder::Respond($data, date('m-d-Y'));
        }
    }

    public function register() {
        if ($this->validPostRequest()) {
            $username = '';
            $password = '';
            if ($_POST['user_name'] != '') {
                $username = $_POST['user_name'];
            }

            if ($_POST['password'] != '') {
                $password = $_POST['password'];
            }


            if (!empty($username) && !empty($password)) {

                $dbUser = Users::model()->find('username=:username', array(':username' => trim($username)));
                if ($dbUser) {
                    $data = new AQResult(501, 'Username ' . $username . ' already registered. Please try again with different user name.');
                } else {
                    $transaction = Yii::app()->getDb()->beginTransaction();   //dbConnection->beginTransaction();
                    try {
                        $createtime = time();
                        $lastvisit = time();
                        $user = new Users();
                        $user->setAttribute('username', trim($username));
                        $user->setAttribute('password', md5($password));
                        $user->setAttribute('createtime', $createtime);
                        $user->setAttribute('lastvisit', $lastvisit);
                        $user->setAttribute('status', 1);
                        $user->save(false);
                        $user->addProfile($_POST);
                        $user->addUserRole(2);
                        $user->saveAppUsersPreferences();
                        $email = $_POST['email'];
                        $msgTpl = 'registration_success.php';
                        $urlPath = 'http://' . Yii::app()->request->getServerName() . Yii::app()->baseUrl;
                        $body = populateEmailTemplate($msgTpl, array('$NAME' => $username, '$PATH' => $urlPath,
                            '$USERNAME' => $username,
                            '$PASSWORD' => $password));

                        anotherEmailSend($email, "Thanks for registering with Why Wait", $body);
                        // anotherEmailSend($email, "User has been successfully registered. Thank you for registering.", $body);
                        //emailSend($username, $email, $password, $msgTpl);
                        $data = new AQResult(200, 'User has been successfully registered. Thank you for registering.');
                        $transaction->commit();
                    } catch (Exception $e) {
                        $transaction->rollBack();
                        $data = $e;
                    }
                }
            } else {
                $data = new AQResult(501, 'Username and Password were empty. Please send valid values and try again.');
            }
        } else {
            $data = new AQResult(501, 'Invalid request parameters. Please check settings and try again.');
        }
        AQApiResponder::Respond($data, date('m-d-Y'));
    }

    /**
     * Api Function to connect facebook
     * 
     */
    public function fbConnect() {
        if ($this->validPostRequest()) {
            if (!isset($_POST['username']) || empty($_POST['username']) || strlen($_POST['username']) < 2) {
                $data = new AQResult(501, 'Username is empty. Please send valid values and try again.');
            } else {

                $dbUser = Users::model()->find('username=:username', array(':username' => trim($_POST['username'])));
                if ($dbUser) {
                    $data = self::getAuthKey($dbUser->id);
                } else {
                    $transaction = Yii::app()->getDb()->beginTransaction();
                    try {
                        $attributes['username'] = $_POST['username'];
                        $attributes['password'] = $_POST['username']; //For Fb connect password not comming. So we use username for password
                        $attributes['createtime'] = time();
                        $attributes['firstname'] = isset($_POST['firstname']) ? $_POST['firstname'] : '';
                        $attributes['lastname'] = isset($_POST['lastname']) ? $_POST['lastname'] : '';
                        $attributes['email'] = isset($_POST['email']) ? $_POST['email'] : '';
                        $dbUser = self::addNewUser($attributes, Roles::FACEBOOKAPPUSER);
                        //After registor fb user return Auth key for login
                        $data = self::getAuthKey($dbUser->id);
                        $transaction->commit();
                    } catch (Exception $e) {
                        $transaction->rollBack();
                        $data = new AQResult(501, $e);
                    }
                }
            }
        }
        AQApiResponder::Respond($data, date('m-d-Y'));
    }

    protected static function addNewUser($attributes, $roleID) {
        $user = new Users();
        $user->setAttributes($attributes);
        $user->setAttribute('username', trim($user->getAttribute('username')));
        $user->setAttribute('password', md5($user->getAttribute('password')));
        $user->save(false);
        $user->addProfile($attributes);
        $user->addUserRole($roleID);
        $user->saveAppUsersPreferences();
        if (!empty($_POST['email'])) {
            $msgTpl = 'registration_success.php';
            $urlPath = 'http://' . Yii::app()->request->getServerName() . Yii::app()->baseUrl;
            $body = populateEmailTemplate($msgTpl, array('$NAME' => $username, '$PATH' => $urlPath,
                '$USERNAME' => $username,
                '$PASSWORD' => $password));

            anotherEmailSend($email, "Thanks for registering with Why Wait", $body);
        }
        return $user;
    }

    protected static function getAuthKey($user_id) {
        $auth = new AuthKey();
        if ($auth->InsertAuthKey($user_id)) {
            $data = array('auth_key' => $auth->getAttribute('auth_key'));
        } else {
            $data = array('auth_key' => NULL);
        }
        return $data;
    }

    function forgotPassword() {
        if ($this->validPostRequest()) {
            $userName = $_POST['username'];
            if (empty($userName)) {
                $data = new AQResult(501, 'Please enter username');
            } else {
                $user = Users::model()->find('username=:username', array(':username' => $userName));
                if (!$user) {
                    $data = new AQResult(501, 'Please enter correct username');
                } else {
                    $profiles = Profiles::model()->find('user_id=:user_id', array(':user_id' => $user->id));
                    if (is_array($profiles)) {

                        $email = $profiles[0]->getAttribute('email');
                    } else {
                        $email = $profiles->getAttribute('email');
                    }

                    if ($email) {
                        $key = guid();
                        $user->activationKey = $key;
                        try {

                            $user->save(false);
                            $msgTpl = 'forgatePasswordTemplate.php';
                            $subject = 'Your Password Link';
                            $activation_url = 'http://' . $_SERVER['HTTP_HOST'] . Yii::app()->createUrl('user/user/recovery', array("activationKey" => $user->activationKey, "username" => $user->username));
                            forgatePasswordEmail($email, $user, $activation_url, $subject, $msgTpl);
                            $data = new AQResult(200, ' Email send successfully.');
                        } catch (Exception $exc) {
                            $data = new AQResult(501, 'Sorry! There is some problem. Please try again later.');
                        }
                    } else {
                        $data = new AQResult(501, 'Email id is not given');
                    }
                }
            }
            AQApiResponder::Respond($data, date('m-d-Y'));
        }
    }

    /* --------------- End POST Actions --------------------- */
}

?>
